{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "9a12e134",
   "metadata": {},
   "source": [
    "# Quickstart\n",
    "\n",
    "## Installation\n",
    "\n",
    "To install TableGPT Agent, use the following command:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fe436583",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install tablegpt-agent"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b81082f9-c74b-4d11-ab1f-2c8c041a29c4",
   "metadata": {},
   "source": [
    "TableGPT Agent depends on pybox to manage code execution environment. By default, pybox operates in an in-cluster mode. If you intend to run tablegpt-agent in a local environment, install the optional dependency as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "4c692b35-0e56-4d3e-b20a-6fefd6dbc9e4",
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "%pip install tablegpt-agent[local]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a55ff4b",
   "metadata": {},
   "source": [
    "\n",
    "This tutorial uses `langchain-openai` for the chat model instance. Please make sure you have it installed:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "503a2807",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install langchain-openai"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b2d82049",
   "metadata": {},
   "source": [
    "## Setup the LLM Service\n",
    "\n",
    "Before using TableGPT Agent, ensure you have an OpenAI-compatible server configured to host TableGPT2. We recommend using [vllm](https://github.com/vllm-project/vllm) for this:\n",
    "\n",
    "```bash\n",
    "python -m vllm.entrypoints.openai.api_server --served-model-name TableGPT2-7B --model path/to/weights\n",
    "```\n",
    "\n",
    "> **NOTES:**\n",
    ">\n",
    "> - To analyze tabular data with `tablegpt-agent`, make sure `TableGPT2` is served with `vllm` version 0.5.5 or higher.\n",
    "> - For production environments, it's important to optimize the vllm server configuration. For details, refer to the [vllm documentation on server configuration](https://docs.vllm.ai/en/v0.6.0/serving/openai_compatible_server.html#command-line-arguments-for-the-server)."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2f0a9ec8",
   "metadata": {},
   "source": [
    "## Create TableGPT Agent\n",
    "\n",
    "> **NOTE:** TableGPT Agent fully supports aync invocation. If you are running this tutorial in a Jupyter Notebook, no additional setup is required. However, if you plan to run the tutorial in a Python console, make sure to use a console that supports asynchronous operations. To get started, execute the following command:\n",
    ">\n",
    "> ```bash\n",
    "> python -m asyncio\n",
    "> ```\n",
    "\n",
    "In the console or notebook, create the agent as follows:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ac32d2f",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "from pybox import AsyncLocalPyBoxManager\n",
    "from tablegpt.agent import create_tablegpt_graph\n",
    "\n",
    "\n",
    "llm = ChatOpenAI(openai_api_base=\"YOUR_VLLM_URL\", openai_api_key=\"whatever\", model_name=\"TableGPT2-7B\")\n",
    "pybox_manager = AsyncLocalPyBoxManager()\n",
    "\n",
    "agent = create_tablegpt_graph(\n",
    "    llm=llm,\n",
    "    pybox_manager=pybox_manager,\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "31ff4fe9",
   "metadata": {},
   "source": [
    "## Start Chatting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ee24c200",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[HumanMessage(content='Hi', additional_kwargs={}, response_metadata={}, id='34fe748c-81ab-49ea-bec6-9c621598a61a'), AIMessage(content=\"Hello! How can I assist you with data analysis today? Please let me know the details of the dataset you're working with and what specific analysis you'd like to perform.\", additional_kwargs={'parent_id': 'some-parent-id'}, response_metadata={}, id='a1ee29d2-723e-41c7-b420-27d0cfaed5dc')]\n"
     ]
    }
   ],
   "source": [
    "from datetime import date\n",
    "from langchain_core.messages import HumanMessage\n",
    "\n",
    "message = HumanMessage(content=\"Hi\")\n",
    "\n",
    "_input = {\n",
    "    \"messages\": [message],\n",
    "    \"parent_id\": \"some-parent-id\",\n",
    "    \"date\": date.today(),\n",
    "}\n",
    "\n",
    "state = await agent.ainvoke(_input)\n",
    "state[\"messages\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3eca819d",
   "metadata": {},
   "source": [
    "You can get more detailed outputs with the `astream_events` method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3265cf83",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "content='Hello! How can I assist you with your data analysis today? Please let me know what dataset you are working with and what specific analyses or visualizations you would like to perform.' additional_kwargs={} response_metadata={'finish_reason': 'stop', 'model_name': 'TableGPT2-7B'} id='run-525eb149-0e3f-4b04-868b-708295f789ac'\n"
     ]
    }
   ],
   "source": [
    "async for event in agent.astream_events(\n",
    "    input=_input,\n",
    "    version=\"v2\",\n",
    "):\n",
    "    # We ignore irrelevant events here.\n",
    "    if event[\"event\"] == \"on_chat_model_end\":\n",
    "        print(event[\"data\"][\"output\"])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
